package com.happy3w.ssp.schoolmatehome.service.auth;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.happy3w.ssp.schoolmatehome.entity.User;
import com.happy3w.ssp.schoolmatehome.exception.MessageException;
import com.happy3w.ssp.schoolmatehome.repository.UserRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

@RequiredArgsConstructor
@Component
public class UserCache {
    private final UserRepository userRepository;
    private final Cache<Long, TheUserDetail> cache = CacheBuilder.newBuilder()
            .expireAfterWrite(6, TimeUnit.HOURS)
            .maximumSize(1000)
            .build();

    public TheUserDetail getUserDetail(Long userId) {
        try {
            return cache.get(userId, () -> loadUser(userId));
        } catch (ExecutionException e) {
            throw new MessageException("failed to load user info:" + userId, e);
        }
    }

    private TheUserDetail loadUser(Long userId) throws Exception {
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new MessageException("User not found with id: " + userId));

        return TheUserDetail.buildNormal(user);
    }
}
